package com.qlhx.wechat.common;

import tools.Guid;

import java.io.*;
import java.net.URL;

/**
 * Created by yxn on 2019-02-28.
 */
public class HardWareUtils {

    /**
     * 获取主板序列号
     *
     * @return
     */
    public static String getMotherboardSN() {
        String result = "";
        try {
            File file = File.createTempFile("realhowto", ".vbs");
            file.deleteOnExit();
            FileWriter fw = new FileWriter(file);

            String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
                    + "Set colItems = objWMIService.ExecQuery _ \n"
                    + "   (\"Select * from Win32_BaseBoard\") \n"
                    + "For Each objItem in colItems \n"
                    + "    Wscript.Echo objItem.SerialNumber \n"
                    + "    exit for  ' do the first cpu only! \n" + "Next \n";

            fw.write(vbs);
            fw.close();
            Process p = Runtime.getRuntime().exec(
                    "cscript //NoLogo " + file.getPath());
            BufferedReader input = new BufferedReader(new InputStreamReader(
                    p.getInputStream()));
            String line;
            while ((line = input.readLine()) != null) {
                result += line;
            }
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.trim();
    }

    /**
     * 获取硬盘序列号
     *
     * @param drive 盘符
     * @return
     */
    public static String getHardDiskSN(String drive) {
        String result = "";
        try {
            File file = File.createTempFile("realhowto", ".vbs");
            file.deleteOnExit();
            FileWriter fw = new FileWriter(file);

            String vbs = "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n"
                    + "Set colDrives = objFSO.Drives\n"
                    + "Set objDrive = colDrives.item(\""
                    + drive
                    + "\")\n"
                    + "Wscript.Echo objDrive.SerialNumber"; // see note
            fw.write(vbs);
            fw.close();
            Process p = Runtime.getRuntime().exec(
                    "cscript //NoLogo " + file.getPath());
            BufferedReader input = new BufferedReader(new InputStreamReader(
                    p.getInputStream()));
            String line;
            while ((line = input.readLine()) != null) {
                result += line;
            }
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.trim();
    }

    /**
     * 获取CPU序列号
     *
     * @return
     */
    public static String getCPUSerial() {
        String result = "";
        try {
            File file = File.createTempFile("tmp", ".vbs");
            file.deleteOnExit();
            FileWriter fw = new FileWriter(file);
            String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
                    + "Set colItems = objWMIService.ExecQuery _ \n"
                    + "   (\"Select * from Win32_Processor\") \n"
                    + "For Each objItem in colItems \n"
                    + "    Wscript.Echo objItem.ProcessorId \n"
                    + "    exit for  ' do the first cpu only! \n" + "Next \n";

            // + "    exit for  \r\n" + "Next";
            fw.write(vbs);
            fw.close();
            Process p = Runtime.getRuntime().exec(
                    "cscript //NoLogo " + file.getPath());
            BufferedReader input = new BufferedReader(new InputStreamReader(
                    p.getInputStream()));
            String line;
            while ((line = input.readLine()) != null) {
                result += line;
            }
            input.close();
            file.delete();
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        if (result.trim().length() < 1 || result == null) {
            result = "无CPU_ID被读取";
        }
        return result.trim();
    }

    /**
     * 获取MAC地址
     */
    public static String getMac() {
        String result = "";
        try {

            Process process = Runtime.getRuntime().exec("ipconfig /all");

            InputStreamReader ir = new InputStreamReader(
                    process.getInputStream());

            LineNumberReader input = new LineNumberReader(ir);

            String line;

            while ((line = input.readLine()) != null)

                if (line.indexOf("Physical Address") > 0) {

                    String MACAddr = line.substring(line.indexOf("-") - 2);

                    result = MACAddr;

                }

        } catch (IOException e) {

            System.err.println("IOException " + e.getMessage());

        }
        return result;
    }


    //获取项目的根路径


    public static String getRootPath() {

        URL url = HardWareUtils.class.getClassLoader().getResource("/");
        if (url == null) {
            return "";
        }
        String classPath = url.getPath();
        String rootPath = "";
        //windows下
        if ("\\".equals(File.separator)) {
            System.out.println("windows");
            rootPath = classPath.substring(1, classPath.indexOf("/WEB-INF/classes"));
            rootPath = rootPath.replace("/", "\\");
        }
        //linux下
        if ("/".equals(File.separator)) {
            System.out.println("linux");
            rootPath = classPath.substring(0, classPath.indexOf("/WEB-INF/classes"));
            rootPath = rootPath.replace("\\", "/");
        }
        File file =new File(rootPath);
        String strParentDirectory = file.getParent();
        return strParentDirectory;
    }

    static String authcode="";


    public static String GetLocalAuthCode(){

        if(authcode!=null&&authcode!=""){
            return  authcode;
        }

        try {
            String path = getRootPath();
            String codepath = path + File.separator + "authcode.txt";
            File file = new File(codepath);

            String code="";

            if (!file.exists()) {
                file.createNewFile();
                BufferedWriter out = new BufferedWriter(new FileWriter(file));
                code = Guid.CreateGUID();
                out.write(code);
                out.flush(); // 把缓存区内容压入文件
                out.close(); // 最后记得关闭文件
                authcode=code;
            }else {
                File filename = new File(codepath); // 要读取以上路径的input。txt文件
                InputStreamReader reader = new InputStreamReader(
                        new FileInputStream(filename)); // 建立一个输入流对象reader
                BufferedReader br = new BufferedReader(reader); // 建立一个对象，它把文件内容转成计算机能读懂的语言
                String line = br.readLine();
                if(line==null||line==""){
                    file.createNewFile();
                    BufferedWriter out = new BufferedWriter(new FileWriter(file));
                    code = Guid.CreateGUID();
                    out.write(code);
                    out.flush(); // 把缓存区内容压入文件
                    out.close(); // 最后记得关闭文件
                    authcode=code;
                }else {
                    authcode = line;
                }
            }

            return authcode;


        } catch (Exception e) {
            e.printStackTrace();
        }

        return  null;
    }

    public static void main(String[] args) {
        System.out.println("文件路径：" + getRootPath());
        System.out.println("CPU  SN:" + HardWareUtils.getCPUSerial());
        System.out.println("主板  SN:" + HardWareUtils.getMotherboardSN());
        System.out.println("C盘   SN:" + HardWareUtils.getHardDiskSN("c"));
        System.out.println("MAC  SN:" + HardWareUtils.getMac());
    }
}
